package com.kotlin.book.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.kotlin.book.adapter.BookItemColumn3Adapter
import com.kotlin.book.adapter.BookItemColumn4Adapter
import com.kotlin.book.adapter.HomeUpdateItemAdapter
import com.kotlin.book.api.BookApi
import com.kotlin.book.databinding.FragmentHomeItemBinding
import com.kotlin.book.entry.Type

class HomeFragmentItem(private var type: Type) : Fragment() {
    private lateinit var binding: FragmentHomeItemBinding
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentHomeItemBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        binding.homeItemFeatured.layoutManager = GridLayoutManager(requireActivity(), 3)
        //精选
        BookApi.getRecommendList(
            mapOf(
                "pageSize" to 3,
                "pid" to type.id,
                "isEnd" to 0
            )
        ) { response ->
            response?.data?.let {
                requireActivity().runOnUiThread {
                    binding.homeItemFeatured.adapter = BookItemColumn3Adapter(it)
                }
            }
        }
        //完结推荐
        binding.homeItemEnd.layoutManager = GridLayoutManager(requireActivity(), 4)
        BookApi.getRecommendList(
            mapOf(
                "pid" to type.id,
                "isEnd" to 1
            )
        ) { response ->
            response?.data?.let {
                requireActivity().runOnUiThread {
                    binding.homeItemEnd.adapter =
                        BookItemColumn4Adapter(mapOf("authorName" to true), it)
                }
            }
        }
        //最近更新
        binding.homeItemUpdate.layoutManager = LinearLayoutManager(context)
        BookApi.getRecommendList(
            mapOf(
                "pid" to type.id,
                "sort" to "updateTime"
            )
        ) { response ->
            response?.data?.let {
                requireActivity().runOnUiThread {
                    binding.homeItemUpdate.adapter = HomeUpdateItemAdapter(it)
                }
            }
        }
    }
}